<?php
class DataHelper extends CComponent {
	public static function getAttention()
	{
		$att = Config::model()->findByPk('attention')->textvalue;
		$arr = explode("\n", $att);
		return implode("<br>",$arr);
	}
	
	public static function getRuleTotCnt()
	{
		$rows = Yii::app()->db->createCommand()->
		select("count(*) as cnt")
		->from('Rule')
		->queryRow();
		return $rows["cnt"];
	}
	
	public static function getRuleClassTotCnt()
	{
		$rows = Yii::app()->db->createCommand()->
		select("count(*) as cnt")
		->from('Rule')
		->group('ruleClass')
		->queryRow();
		return $rows["cnt"];
	}
	public static function getDistribution()
	{
		$rows = Yii::app()->db->createCommand()->
		select("count(*) as cnt,ruleClass")
		->from('Rule')
		->group('ruleClass')
		->order('cnt desc')
		->queryAll();
		$ret = array();
		$cnt = 0;
		foreach ($rows as $row) {
			$ret[$cnt] = array($row["ruleClass"],(int)($row["cnt"]));
			$cnt ++;
		}
		return $ret;
	}
	public static function getRecmId($ruleClass)
	{
		$maxId = Yii::app()->db->createCommand()
    	->select('max(sid) as MS')
    	->from('Rule')
    	->where('ruleClass=:rc', array(':rc'=>$ruleClass))
    	->queryRow();
		return $maxId["MS"];
	}
	/**
	 * @param boolean $isNew
	 * @return recent 5 rules modified or added
	 */
	public static function getRecentHistory($isNew)
	{
		$ret = array();
		$cnt = 0;
		$criteria = new CDbCriteria();
		$criteria->distinct = true;
		$criteria->select = "historyRule";
		$reason = $isNew?"add":"modify";
		$criteria->addColumnCondition(array("historyReason"=>$reason));
		$criteria->order = "rid desc";
		$criteria->group="rid";
		$criteria->limit = 5;
		$rows = RuleHistory::model()->findAll($criteria);
		return $rows;
	}
	/**
	 * @param integer $rid
	 * @return get history rules for rule {rid}
	 */
	public static function genHistoryDrop($rid) {
		$histories = RuleHistory::model()->findAllByAttributes(array("rid"=>$rid));
		$ret = array();
		$cnt = 0;
		foreach ($histories as $history) {
			$content = $history->historyRule;
			$ret[$cnt]=array('label'=>$history->rid,'url'=>"javascript:changeTo('".rawurlencode(($content))."')");
			$cnt++;
		}
		return $ret;
	}
	/**
	 * @param integer $id
	 * get max sid of this file
	 */
	public function actionGetProId($id)
	{
		$criteria = new CDbCriteria();
		$criteria->addColumnCondition(array("categoryId"=>$id));
		$criteria->select = 'MAX(sid) AS maxSid';
		$row = Rule::model()->find($criteria);
		echo $row["maxSid"];
		Yii::app()->end();
	}
	
	public static function getClassList()
	{
		$ret = array();
		$cnt = 0;
		$criteria = new CDbCriteria();
		$criteria->distinct = true;
		$criteria->select = "ruleClass";
		$rows = Rule::model()->findAll($criteria);
		foreach ($rows as $row) {
			$ret[$cnt] = $row->ruleClass;
			$cnt ++;
		}	
		return $ret;
	}
}

?>